package servicios.biziGasteiz;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ListIterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import connection.BDConnection;

/**
 * Servlet implementation class ConcertsServices
 */
public class UserServices extends HttpServlet {
	private static final long serialVersionUID = 1L;

    private String CONTENT_TYPE = "text/json";
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServices() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {

			processRequest(request, response);

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			e.printStackTrace();
		}
	}
	
	
	
	private void processRequest(HttpServletRequest request, HttpServletResponse  response) throws SQLException, IOException, ClassNotFoundException{
		response.setContentType(CONTENT_TYPE);
		String requestP = request.getParameter("request");
		try{
			if(requestP.compareToIgnoreCase("UPLOADPHOTO") == 0){
				uploadPhoto(request, response);
			}
		}catch(Exception e){
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			e.printStackTrace();
		}
	}
	
	private void uploadPhoto(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ClassNotFoundException{
		try{
			List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			ListIterator iterator = items.listIterator();
			String username = request.getParameter("username");
	        while (iterator.hasNext()) {
	        	FileItem item = (FileItem) iterator.next();
	            if (!item.isFormField()) {
	                //String filename = item.getName();
	                InputStream filecontent = item.getInputStream();
	                String relativePath = request.getSession().getServletContext().getRealPath("/images/users");
	                File f=new File(relativePath+File.separator+username);
	                OutputStream os=new FileOutputStream(f);
	                byte[] buf =new byte[1024];
	                int len;
	                while((len=filecontent.read(buf))>0){
	                	os.write(buf,0,len);
	                }
	                os.close();
	                filecontent.close();
	            }
	        }
	        response.getWriter().print("1");
		}
		catch(Exception oo){
			
		}
	}
}
